package com.example.close_order.service;

import com.example.close_order.entity.Order;
import com.example.close_order.repository.OrderRepository;
import com.example.close_order.scheduler.OrderCloseScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class OrderService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderCloseScheduler orderCloseScheduler;
    
    /**
     * 创建订单并设置自动关闭任务
     */
    @Transactional
    public Order createOrder(Long userId, BigDecimal amount, Integer closeTimeoutMinutes) {
        // 生成唯一订单号
        String orderNo = generateOrderNo();
        
        // 计算过期时间
        LocalDateTime expireTime = LocalDateTime.now()
                .plusMinutes(closeTimeoutMinutes);
        
        // 创建订单
        Order order = new Order(orderNo, userId, amount, expireTime);
        Order savedOrder = orderRepository.save(order);
        
        // 设置Redisson分布式延迟任务
        orderCloseScheduler.scheduleOrderClose(
                orderNo, 
                closeTimeoutMinutes, 
                TimeUnit.MINUTES
        );
        
        return savedOrder;
    }
    
    /**
     * 根据订单号获取订单
     */
    public Order getOrderByNo(String orderNo) {
        return orderRepository.findByOrderNo(orderNo)
                .orElseThrow(() -> new RuntimeException("订单不存在: " + orderNo));
    }
    
    /**
     * 更新订单状态（例如支付成功）
     */
    @Transactional
    public Order updateOrderStatus(String orderNo, String status) {
        Order order = getOrderByNo(orderNo);
        
        // 如果订单状态变为已支付，取消自动关闭任务
        if ("PAID".equals(status)) {
            orderCloseScheduler.cancelOrderCloseTask(orderNo);
        }
        
        // 更新订单状态逻辑...
        return order;
    }
    
    /**
     * 生成唯一订单号
     */
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + 
               UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }
}